package com.uw.uwregistry.health;


import com.uw.uwregistry.meta.InstanceMeta;
import com.uw.uwregistry.service.RegistryContainer;
import com.uw.uwregistry.service.RegistryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
@RequiredArgsConstructor
public class UWHealthChecker implements HealthChecker {

    final RegistryService registryService;

    final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);

    long timeout = 20_000;


    @Override
    public void start() {
        executorService.scheduleWithFixedDelay(() -> {
            try {
                log.debug(" ==> start health check");
                Map<String, Long> heartbeatMap = RegistryContainer.heartbeatMap();

                long now = System.currentTimeMillis();

                for (Map.Entry<String, Long> entry : heartbeatMap.entrySet()) {
                    String serviceInstance = entry.getKey();
                    Long lastHeartbeatTime = entry.getValue();
                    if (now - lastHeartbeatTime > timeout) {
                        log.debug(" ==> {} timeout", serviceInstance);
                        String service = serviceInstance.split("@")[0];
                        String instanceUrl = serviceInstance.split("@")[1];

                        registryService.unregister(service, InstanceMeta.fromUrl(instanceUrl));
                        RegistryContainer.removeHeartbeatMap(serviceInstance);
                    }
                }
            } catch (Exception ex) {
                log.error(" ===> UWHealthChecker start scheduleWithFixedDelay exception.",ex);
            }
        }, 0, 5, TimeUnit.SECONDS);
    }

    @Override
    public void stop() {
        executorService.shutdown();
    }
}
